import { Scene } from "../../../../../Core/Module/Entity/Scene";
import { EventSystem } from "../../../../../Core/Module/EventSystem/EventSystem";
import { EventType } from "../../../../Model/Share/Demo/EventType";
import { AIComponent } from "../../../../Model/Share/Module/AI/AIComponent";
import { ObjectWait } from "../../../../Model/Share/Module/ObjectWait/ObjectWait";
import { CurrentScenesComponent } from "../../../../Model/Share/Module/Scene/CurrentScenesComponent";
import { UnitComponent } from "../../../../Model/Share/Module/Unit/UnitComponent";
import { UnitFactory } from "../Unit/UnitFactory";
import { WaitType } from "../WaitType";
import { SceneFactory } from "./SceneFactory";

export class SceneChangeHelper {

    public static async SceneChangeTo(zoneScene: Scene, sceneName: string, sceneInstanceId: number) {
        zoneScene.RemoveComponent<AIComponent>(AIComponent);

        let currentScenesComponent = zoneScene.GetComponent<CurrentScenesComponent>(CurrentScenesComponent);
        currentScenesComponent.Scene?.Dispose(); // 删除之前的CurrentScene，创建新的
        let currentScene = SceneFactory.CreateCurrentScene(sceneInstanceId, zoneScene.Zone, sceneName, currentScenesComponent);
        let unitComponent = currentScene.AddComponent<UnitComponent>(UnitComponent);

        // 可以订阅这个事件中创建Loading界面
        let sceneChangeStart = new EventType.SceneChangeStart();
        sceneChangeStart.ZoneScene = zoneScene;
        EventSystem.Instance.Publish(currentScene, sceneChangeStart);

        // 等待CreateMyUnit的消息
        let waitCreateMyUnit = await zoneScene.GetComponent<ObjectWait>(ObjectWait).Wait<WaitType.Wait_CreateMyUnit>(WaitType.Wait_CreateMyUnit);
        let m2CCreateMyUnit = waitCreateMyUnit.Message;
        let unit = UnitFactory.Create(currentScene, m2CCreateMyUnit.Unit);
        unitComponent.Add(unit);

        zoneScene.RemoveComponent<AIComponent>(AIComponent);

        let sceneChangeFinish = new EventType.SceneChangeFinish();
        sceneChangeFinish.ZoneScene = zoneScene;
        sceneChangeFinish.CurrentScene = currentScene;
        EventSystem.Instance.Publish(zoneScene, sceneChangeFinish);

        // 通知等待场景切换的协程
        zoneScene.GetComponent<ObjectWait>(ObjectWait).Notify(new WaitType.Wait_SceneChangeFinish());
    }

}